using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace lwzlz.Application.System
{
    public class ShoppingCartService
    {
        private readonly IRepository<ShoppingCart> _repository;

        public ShoppingCartService()
        {
            _repository = new Repository<ShoppingCart>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ShoppingCart Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<dynamic> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 字段
            var select = @"
                t1.*,
                t2.Name AS CommodityName,
                t2.Money AS CommodityMoney,
                (t1.Number * t2.Money) AS TotalMoney,
                t3.UserName AS MemberUserName,
                t3.RealName AS MemberRealName";
            #endregion

            #region 表
            var table = @"
                    dbo.Ser_ShoppingCart t1
                LEFT JOIN dbo.Ser_Commodity t2
                    ON t2.Id = t1.CommodityId
                LEFT JOIN dbo.Ser_Member t3
                    ON t3.Id = t1.MemberId";
            #endregion

            #region 参数查询

            string where = " t1.IsDeleted=0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //商品名称
            if (dic_conditions.ContainsKey("CommodityName"))
            {
                dic.Add("@CommodityName", dic_conditions["CommodityName"]);
                where += " AND t2.Name=@CommodityName ";
            }
            //用户名
            if (dic_conditions.ContainsKey("MemberUserName"))
            {
                dic.Add("@MemberUserName", dic_conditions["MemberUserName"]);
                where += " AND t3.UserName=@MemberUserName ";
            }
            //用户姓名
            if (dic_conditions.ContainsKey("MemberRealName"))
            {
                dic.Add("@MemberRealName", dic_conditions["MemberRealName"]);
                where += " AND t3.RealName=@MemberRealName ";
            }

            #endregion

            #region 排序

            //排序sql语句拼接
            string orderby = " t1.CreationTime DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var sql = $"SELECT {select} FROM {table} WHERE {where} ";

            var list = _repository.GetDynamicPaged(pageNumber, rowsPerPage, orderby, sql, dic);

            count = _repository.RecordQueryCount(sql, dic);

            return Mapper.Map<List<dynamic>>(list);
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public List<ShoppingCart> GetShoppingCartList(int memberId)
        {
            var where = @" WHERE IsDeleted = 0 AND MemberId = @MemberId";
            var list = _repository.GetList(where, new { MemberId = memberId }).ToList();
            return list;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public ShoppingCart Get(int memberId, int commodityId)
        {
            var where = @" WHERE IsDeleted = 0 AND MemberId = @MemberId AND CommodityId = commodityId";
            var entity = _repository.GetList(where, new { MemberId = memberId, CommodityId = commodityId }).FirstOrDefault();
            return entity;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public List<MemberShoppingCart> GetList(int memberId)
        {
            var sql = @"
                SELECT b.*,a.CommodityId,a.Number as ShoppingCartNumber
                FROM Ser_ShoppingCart a
                    LEFT JOIN dbo.Ser_Commodity b
                        ON b.Id = a.CommodityId
                WHERE a.IsDeleted = 0
                      AND a.MemberId = @MemberId";

            var list = _repository.Query<MemberShoppingCart>(sql, new { MemberId = memberId }).ToList();
            return list;
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? Insert(ShoppingCart entity, IDbTransaction dbtran)
        {
            return _repository.Insert(entity, dbtran);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(ShoppingCartInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<ShoppingCart>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;

                int? Id = _repository.Insert(entity, dbtran);

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Update(ShoppingCart entity, IDbTransaction dbtran)
        {
            return _repository.Update(entity, dbtran);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(ShoppingCartInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    ShoppingCart model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        #endregion
    }
}

